<?php

/*
 * Author: Quan Van Sinh
 * Email : qvsinh@gmail.com
 * Mobile: 0972405165
 */

class member {

    function member() {
        
    }

    public static function checkRememberLogin() {
        global $db;
        $_COOKIE['saveLogin'];
        if (isset($_COOKIE['saveLogin'])) {
            $arrParams = explode('|', $_COOKIE['saveLogin']);
            $email = $arrParams[0];
            $password = $arrParams[1];
            if (!empty($email) && !empty($password)) {
                $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND email='$email' AND password='$password' AND active=1";
                $rs = $db->query_first($sql);
                if ($rs['id']) {
                    return TRUE;
                } else {
                    return FALSE;
                }
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    function login() {
        global $db;
        if (isset($_POST['email'])) {
            $email = trim($_POST['email']);
            if (isset($_POST['rememberLogin'])) {
                $password = trim($_POST['password']);
            } else {
                $password = md5(trim($_POST['password']));
            }
            $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND email='$email' AND password='$password' AND active=1";
            $rs = $db->query_first($sql);
            if ($rs['id']) {
                $_SESSION['client'] = $rs;
                if (isset($_POST['chkSaveLogin']) && intval($_POST['chkSaveLogin']) == 1) {
                    setcookie('saveLogin', $email . '|' . $password, time() + 60 * 60 * 24 * 7);
                }
                header("Location: /quan-ly-chi-tieu");
            } else {
                return FALSE;
            }
        } else {
            if (isset($_SESSION['client']))
                unset($_SESSION['client']);
            return FALSE;
        }
    }

    function logout() {
        unset($_SESSION['client']);
    }

    function checkLogin() {
        if (isset($_SESSION['client']['id'])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    function checkLoginRedirect() {
        if (isset($_SESSION['client']['id'])) {
            return TRUE;
        } else {
            header("Location: /dang-nhap");
        }
    }

    function isOwner() {
        if ($_SESSION['client']['id'] == intval($_GET['mid'])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function changePassword() {
        global $db;
        if (isset($_POST['oldPassword'])) {
            $mid = $_SESSION['client']['id'];
            $oldPassword = md5($_POST['oldPassword']);
            $newPassword = md5($_POST['newPassword']);
            $rePassword = md5($_POST['rePassword']);

            $sqlCheck = "SELECT * FROM member WHERE id=$mid AND password='$oldPassword'";
            $arrCheck = $db->query_first($sqlCheck);
            if ($arrCheck['id']) {
                if ($newPassword != $rePassword) {
                    return 'password_not_match';
                } else {
                    $sqlUpdate = "UPDATE member SET password='$newPassword' WHERE id=$mid";
                    $db->query($sqlUpdate);
                    return 'ok';
                }
            } else {
                return 'old_password_not_match';
            }
        }
    }

    function deleteImage($id=0) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if ($id && $mid) {
            $sql = "SELECT * FROM images WHERE id=$id AND mid=$mid";
            $arrCheck = $db->query_first($sql);
            if ($arrCheck['id']) {
                if (file_exists($_SERVER ['DOCUMENT_ROOT'] . $arrCheck['image'])) {
                    unlink($_SERVER ['DOCUMENT_ROOT'] . $arrCheck['image']);
                }
                if (file_exists($_SERVER ['DOCUMENT_ROOT'] . $arrCheck['real_image'])) {
                    unlink($_SERVER ['DOCUMENT_ROOT'] . $arrCheck['real_image']);
                }
                $db->query("DELETE FROM images WHERE id=$id AND mid=$mid");
                $db->query("DELETE FROM image_comment WHERE image_id=$id AND mid=$mid");
                return 'ok';
            } else {
                return 'die';
            }
        } else {
            return 'not_login';
        }
    }

    function deleteAlbum($id=0) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if ($id && $mid) {
            $sql = "SELECT count(*) as num FROM images WHERE aid=$id AND mid=$mid and active=1";
            $arrCheck = $db->query_first($sql);
            if ($arrCheck['num'] == 0) {
                $db->query("DELETE FROM album WHERE id=$id AND mid=$mid");
                return 'ok';
            } else {
                return 'not_empty';
            }
        } else {
            return 'not_login';
        }
    }

    function sendMail() {
        global $db;
        if (isset($_POST['to'])) {
            include MODEL_DIR . 'validate.class.php';
            $validate = new validate();

            $idFrom = $_SESSION['client']['id'];
            $arrTo = explode(',', trim($_POST['to']));
            $title = trim($_POST['title']);
            $message = trim($_POST['message']);
            $create_date = date('Y-m-d h:i:s');

            if (empty($_POST['to'])) {
                return 'to_empty';
                die;
            }
            if (empty($_POST['title'])) {
                return 'title_empty';
                die;
            }
            if (empty($_POST['message'])) {
                return 'message_empty';
                die;
            }
            /*
              foreach ($arrEmail as $key => $email) {
              if (!$validate->email($email)) {
              return 'email_invalid';
              die;
              }
              }
             * 
             */
            $data = array();
            $data['id_from'] = $idFrom;
            $data['title'] = $title;
            $data['content'] = $message;
            $data['create_date'] = $create_date;
            if ($idFrom) {
                foreach ($arrTo as $key => $id) {
                    $sqlCheckExist = "SELECT * FROM member WHERE id='$id'";
                    $arrCheck = $db->query_first($sqlCheckExist);
                    if ($arrCheck['id']) {//gui tin nhan cho nhung thanh vien da hoat dong tren he thong
                        $data['id_to'] = $id;
                        $db->exec_insert('message', $data);
                    }
                }
                return 'ok';
            }
        }
    }

    function countInbox() {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT COUNT(id) as total FROM message WHERE id_to='$mid' AND `read`=0 AND receiver_delete=0";
            $rs = $db->query_first($sql);
            return $rs['total'];
        } else {
            return FALSE;
        }
    }

    function markAsRead() {
        global $db;
        $mid = $_SESSION['client']['id'];
        $msg_id = intval($_POST['msg_id']);
        if (intval($mid) && $msg_id) {
            $sql = "UPDATE message SET `read`=1 WHERE id=$msg_id";
            $db->query($sql);
            return TRue;
        } else {
            return FALSE;
        }
    }

    function mailInbox() {
        global $db;
        $id = $_SESSION['client']['id'];
        $sql = "SELECT * FROM message WHERE id_to='$id' AND receiver_delete=0 ORDER BY id DESC";
        $rs = $db->query($sql);
        $arrInbox = array();
        while ($row = $db->fetch_array($rs)) {
            $arrInbox[$row['id']] = $row;
            $id_from = $row['id_from'];
            $sqlSender = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND id='$id_from'";
            $rsSender = $db->query_first($sqlSender);
            $arrInbox[$row['id']]['sender'] = $rsSender;
        }
        return $arrInbox;
    }

    function mailSent() {
        global $db;
        $mid = $_SESSION['client']['id'];
        $sql = "SELECT * FROM message WHERE id_from='$mid' AND sender_delete=0 AND type=0 ORDER BY id DESC";
        $rs = $db->query($sql);
        $arrInbox = array();
        while ($row = $db->fetch_array($rs)) {
            $arrInbox[$row['id']] = $row;
            $id_to = $row['id_to'];
            $sqlReceiver = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND id='$id_to'";
            $rsReceiver = $db->query_first($sqlReceiver);
            $arrInbox[$row['id']]['sender'] = $rsReceiver;
        }
        return $arrInbox;
    }

    function deleteMail($id, $option='') {
        global $db;
        $mid = $_SESSION['client']['id'];
        if ($id && $option != '') {
            if ($option == 'inbox') {
                $sql = "UPDATE message SET receiver_delete=1 WHERE id=$id AND id_to=$mid";
            } else if ($option == 'sent') {
                $sql = "UPDATE message SET sender_delete=1 WHERE id=$id AND id_from=$mid";
            }
            $db->query($sql);
            $db->query("DELETE FROM message WHERE sender_delete=1 AND receiver_delete=1");
        }
        return true;
    }

    function listMyAlbum($limit=50) {
        global $db;
        $mid = intval($_GET['mid']);

        if ($mid) {
            $page = intval($_GET['page']);

            if ($page < 1) {
                $page = 1;
            }

            $sql = "SELECT count(*) as numrows FROM album WHERE mid=$mid";
            $arrTotalRows = $db->query_first($sql);
            $totalPages = ceil($arrTotalRows['numrows'] / $limit);
            $start = (($page * $limit) - $limit);

            $sql = "SELECT a.*,(SELECT image FROM images WHERE aid=a.id AND mid=$mid and active=1 LIMIT 1) as thumb,(select count(*) FROM images WHERE aid=a.id AND mid=$mid and active=1) as count_num  FROM album a WHERE a.mid=$mid order by count_num desc LIMIT $start,$limit";
            $rs = $db->query($sql);
            return array('rs' => $rs, 'page' => $page, 'totalPage' => $totalPages);
        } else {
            return false;
        }
    }

    function listMyImage($limit=50) {
        global $db;
        $mid = intval($_GET['mid']);
        $aid = intval($_GET['aid']);
        if ($mid && $aid) {
            $page = intval($_GET['page']);
            if ($page < 1) {
                $page = 1;
            }

            $sql = "SELECT count(*) as numrows FROM images WHERE mid=$mid AND aid=$aid and active=1";
            $arrTotalRows = $db->query_first($sql);
            $totalPages = ceil($arrTotalRows['numrows'] / $limit);
            $start = (($page * $limit) - $limit);

            $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$aid and active=1 LIMIT $start,$limit";
            $rs = $db->query($sql);

            $sql = "SELECT * FROM album WHERE id=$aid";
            $arrAlbum = $db->query_first($sql);
            return array('rs' => $rs, 'arrAlbum' => $arrAlbum, 'page' => $page, 'totalPage' => $totalPages);
        } else {
            return false;
        }
    }

    function getMyImageExcept($mid, $album_id, $except_id, $limit=9) {
        global $db;
        if ($mid && $album_id) {
            $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$album_id AND id!=$except_id and active=1 LIMIT 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return false;
        }
    }

    function viewImage() {
        global $db;
        $mid = intval($_GET['mid']);
        $aid = intval($_GET['aid']);
        $image_id = intval($_GET['image_id']);

        $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$aid AND id=$image_id LIMIT 1";
        $arrRs = $db->query_first($sql);
        
        if($arrRs['id']){
            $db->query("UPDATE images SET num_views=num_views+1 WHERE id = $image_id");
        }

        $sqlComment = "SELECT * FROM image_comment WHERE 1 AND image_id=$image_id";
        $rsComment = $db->query($sqlComment);

        $sql = "SELECT * FROM images WHERE mid=$mid  AND aid=$aid AND id<$image_id ORDER BY id DESC LIMIT 1";
        $arrPre = $db->query_first($sql);

        $sql = "SELECT * FROM images WHERE mid=$mid  AND aid=$aid AND id>$image_id ORDER BY id LIMIT 1";
        $arrNext = $db->query_first($sql);

        return array('arrRs' => $arrRs, 'rsComment' => $rsComment, 'arrPre' => $arrPre, 'arrNext' => $arrNext);
    }

    function profile() {
        global $db;

        $mid = intval($_GET['mid']);
        $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$mid";
        if ($mid) {
            $profile = $db->query_first($sql);
            if ($profile['geo_id']) {
                $sqlGeo = "SELECT * FROM geographic WHERE id=" . $profile['geo_id'];
                $arrGeo = $db->query_first($sqlGeo);
                $profile['city_id'] = intval($arrGeo['parent_id']);
                $sqlDistricts = "SELECT * FROM geographic WHERE parent_id=" . $profile['city_id'];
                $rsDistricts = $db->query($sqlDistricts);
            }
            return array('profile' => $profile, 'rsDistricts' => $rsDistricts);
        }
    }

    function getAvatar() {
        global $db;
        $mid = $_SESSION['client']['id'];
        $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$mid";
        $rs = $db->query_first($sql);
        return $rs['avatar'];
    }

    function getById($id) {
        global $db;
        if ($id > 0) {
            $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getByName($name) {
        global $db;
        if (strlen(trim($name)) > 0) {
            $sql = "SELECT id,CONCAT(first_name,' ',last_name) as name,email,avatar FROM member where CONCAT(first_name,' ',last_name) like '%$name%' and  LIMIT 10";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getFriendByName($name) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (strlen(trim($name)) > 0) {
            $sql = "SELECT m.id,CONCAT(first_name,' ',last_name) as name,email,avatar FROM member as m inner join friend as f on m.id=f.friend_id where f.mid=$mid AND CONCAT(first_name,' ',last_name) like '%$name%'";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getGeoById($geo_id) {
        global $db;
        if (intval($geo_id)) {
            $sql = "SELECT * FROM geographic WHERE id=$geo_id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAlbumById() {
        global $db;
        $albumId = intval($_GET['id']);
        $mid = $_SESSION['client']['id'];
        if (intval($albumId)) {
            $sql = "SELECT * FROM album WHERE id=$albumId AND mid=$mid";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function updateImageView($image_id) {
        global $db;
        if (intval($image_id)) {
            $sql = "UPDATE image SET num_views=num_views+1 WHERE id=$image_id";
            $rs = $db->query($sql);
            return TRue;
        } else {
            return FALSE;
        }
    }

    function getAllAlbum() {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT * FROM album WHERE mid=$mid";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAllGroup() {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT * FROM groups WHERE mid=$mid";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAllFriend($limit=30) {
        global $db;
        $mid = $_GET["mid"];
        $geo_id = $_SESSION['client']['geo_id'];
        if (intval($mid)) {
            $sql = "SELECT m.*,CONCAT(first_name,' ', last_name) as fullname,groups from member m inner join friend f on m.id=f.friend_id where f.mid=$mid order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getNotFriend($limit) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname from member where id NOT in (select friend_id FROM friend WHERE mid=$mid) and id!=$mid order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getFriendInGroup($gid, $limit) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT m.id as mid,m.avatar,CONCAT(first_name,' ', last_name) as fullname from member as m inner join friend as f on m.id=f.friend_id where groups like '%|$gid|%' order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function addGroup($groupName, $groupDesc='') {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {

            $data = array();
            $data['group_name'] = $groupName;
            $data['length'] = 0;
            $data['mid'] = $mid;
            $data['description'] = $groupDesc;

            $db->exec_insert('groups', $data);
            $group_id = $db->mysql_insert_id();
            return $group_id;
        } else {
            return FALSE;
        }
    }

    function deleteGroup($group_id) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid) && $group_id) {
            $sql = "SELECT * FROM groups where id=$group_id";
            $rsCheck = $db->query_first($sql);
            if ($rsCheck['length'] > 0) {
                return 'not_empty';
            } else {
                $sql = "DELETE FROM groups where id=$group_id";
                $rsCheck = $db->query($sql);
                return 'ok';
            }
        } else {
            return FALSE;
        }
    }

    function addFriend($friendID, $group_id="") {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $data = array();
            $data['friend_id'] = $friendID;
            $data['groups'] = "|" . $group_id . "|";
            $data['mid'] = $mid;


            $sql = "SELECT * from friend where mid=$mid and friend_id=$friendID";
            $rs = $db->query($sql);

            if ($db->num_rows($rs) <= 0) {
                $db->exec_insert('friend', $data);
                if ($group_id > 0)
                    $db->query("UPDATE groups SET length=length+1 WHERE id=$group_id");
            } else {
                $rsCheck = $db->query("SELECT * from friend where mid=$mid and friend_id=$friendID and groups like '%|" . $group_id . "|%'");
                if ($db->num_rows($rsCheck) <= 0) {
                    $db->query("UPDATE friend SET groups=concat(groups,'" . $group_id . "|') WHERE mid=$mid and friend_id=$friendID");
                    if ($group_id > 0)
                        $db->query("UPDATE groups SET length=length+1 WHERE id=$group_id");
                } else {
                    return '0';
                }
            }
            return '1';
        } else {
            return '-1';
        }
    }

    function removeFriendFromGroup($friendID, $group_id) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $updatesql = "UPDATE friend SET groups=replace(groups,'" . $group_id . "|','') WHERE mid=$mid and friend_id=$friendID and groups like '%|" . $group_id . "|%'";
            $db->query($updatesql);
            if ($group_id > 0)
                $db->query("UPDATE groups SET length=length-1 WHERE id=$group_id");
            return '1';
        } else {
            return '-1';
        }
    }

    function searchFriend($keyword, $group_id="", $limit=50) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if ($group_id != "")
            $group_id = "|" . $group_id . "|";
        if (intval($mid)) {
            $sql = "SELECT m.*,CONCAT(first_name,' ', last_name) as fullname FROM member as m inner join friend as f on m.id=f.friend_id WHERE f.mid=$mid and CONCAT(first_name,' ', last_name) LIKE '%$keyword%' and groups like '%$group_id%' order by CONCAT(first_name,' ', last_name) limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function searchMember($limit=NUM_ROW_PER_PAGE) {
        global $db;
        include_once MODEL_DIR . 'validate.class.php';
        $validate = new validate();
        $mid = $_SESSION['client']['id'];
        $geo_id = intval($_SESSION['client']['geo_id']);
        $keyword = trim(mysql_real_escape_string($_GET['keyword']));
        if ($keyword) {
            if ($validate->email($keyword)) {
                $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND email='$keyword'";
                $rs = $db->query($sql);
                return array(
                    'rs' => $rs,
                    'totalPage' => 1,
                    'page' => 1
                );
            } else if (intval($mid)) {

                $page = intval($_GET['page']);
                if ($page <= 0) {
                    $page = 1;
                }

                $sqlTotal = "SELECT count(id) as total FROM member WHERE 1 AND id!=$mid AND CONCAT(first_name,' ', last_name) LIKE '%$keyword%'";
                $totalRow = $db->query_first($sqlTotal);
                $totalPage = ceil($totalRow['total'] / NUM_ROW_PER_PAGE);
                $start = (($page * NUM_ROW_PER_PAGE) - NUM_ROW_PER_PAGE);

                $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND id!=$mid AND  CONCAT(first_name,' ', last_name) LIKE '%$keyword%' limit $start,$limit";
                $rs = $db->query($sql);

                return array(
                    'rs' => $rs,
                    'totalPage' => $totalPage,
                    'page' => $page
                );
            } else {
                return FALSE;
            }
        }
    }

    function getNotifyImage($mid, $imgIds, $limit=3) {
        global $db;
        $rs = FALSE;
        if ($imgIds) {
            $sql = "SELECT * FROM images WHERE 1 AND mid=$mid AND id IN ($imgIds) AND active=1 ORDER BY id DESC LIMIT $limit";
            $rs = $db->query($sql);
        }
        return $rs;
    }

    function getMemberByGroupId($group_id) {
        global $db;
        $rs = FALSE;
        if ($group_id) {
            $sql = "SELECT * FROM friend WHERE 1 AND groups LIKE '%|$group_id|%'";
            $rs = $db->query($sql);
        }
        return $rs;
    }

    function getByImageId($id) {
        global $db;
        if ($id > 0) {
            $sql = "SELECT * FROM images where id=$id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getImageCommentByImageId($image_id) {
        global $db;
        if ($image_id > 0) {
            $sqlComment = "SELECT * FROM image_comment WHERE 1 AND image_id=$image_id";
            $rsComment = $db->query($sqlComment);
            while ($row = $db->fetch_array($rsComment)) {
                $rs[$row['mid']] = $row;
            }
            return $rs;
        } else {
            return FALSE;
        }
    }
    
    function addActivities($mid,$content){
        global $db;
        if($mid && !empty ($content)){
            $data = array();
            $data['mid'] = $mid;
            $data['content'] = $content;
            $data['create_date'] = date('Y-m-d h:i:s');
            $db->exec_insert("activities", $data);
        }
    }
    
    function getActivities($limit=10){
        global $db;
        
        $mid = $_SESSION['client']['id'];
        $rs = array();
        if($mid){
            $sql = "SELECT * FROM activities WHERE 1 AND mid!=$mid ORDER BY id DESC LIMIT $limit";
            $rsA = $db->query($sql);
            while ($row = $db->fetch_array($rsA)) {
                $memberInfo = $this->getById($row['mid']);
                $row['memInfo'] = $memberInfo;
                $rs[] = $row;
            }
            return $rs;
        }else{
            return FALSE;
        }
    }
    function getActivitiesByLastId($last_id,$limit=10){
        global $db;
        
        $mid = $_SESSION['client']['id'];
        $rs = array();
        if($mid){
            $sql = "SELECT * FROM activities WHERE 1 AND id<$last_id AND mid!=$mid ORDER BY id DESC LIMIT $limit";
            $rsA = $db->query($sql);
            while ($row = $db->fetch_array($rsA)) {
                $memberInfo = $this->getById($row['mid']);
                $row['memInfo'] = $memberInfo;
                $rs[] = $row;
            }
            return $rs;
        }else{
            return FALSE;
        }
    }

}

?>
